const { db } = require("../../db/db2");
const moment = require("moment");

async function CreatePins(req, res) {
  const {
    ArticleContent,
    Attachment,
    UrlTitle,
    RealyUrl,
    ActivityId,
    CircleId,
    CircleTypeId,
  } = req.body;
  console.log("req.body", req.body);

  const PublisherId = Number(req.params.username);
  const PublishTime = moment().format("YYYY-MM-DD HH:mm:ss");

  const insert_article = `
    INSERT INTO pin 
    (PinContent, UrlTitle, RealyUrl, ActivityId, CircleId, CircleTypeId, PublisherId, PublishTime)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `;

  // 获取连接池中的连接并执行事务
  const connection = await db.promise().getConnection();

  try {
    // 开始事务
    await connection.beginTransaction();

    // 插入Pin数据
    const [result] = await connection.query(insert_article, [
      ArticleContent,
      UrlTitle,
      RealyUrl,
      ActivityId,
      CircleId,
      CircleTypeId,
      PublisherId,
      PublishTime,
    ]);

    const PinId = result.insertId; // 获取插入的PinId

    // 插入附件数据
    if (Attachment && Attachment.length > 0) {
      const insert_attachment = `
        INSERT INTO PinAttachment (PinId, Url, CreateTime, CreateUser)
        VALUES (?, ?, ?, ?)
      `;

      const attachmentPromises = Attachment.map((file) =>
        connection.query(insert_attachment, [
          PinId,
          file.url,
          PublishTime,
          PublisherId,
        ])
      );

      // 等待所有附件插入完成
      await Promise.all(attachmentPromises);
    }

    // 提交事务
    await connection.commit();

    res.send({ status: 0, PinId });
  } catch (err) {
    // 如果有任何错误，回滚事务
    await connection.rollback();
    console.error("Error:", err);
    res.send({ Message: "插入数据失败", status: 1 });
  } finally {
    // 释放连接
    connection.release();
  }
}

module.exports = { CreatePins };
